package com.sjm.bookshop.controller.upload;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.sjm.bookshop.config.TencentCos;
import com.sjm.bookshop.config.TencentCosConfig;
import com.sjm.bookshop.utils.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * 上传图片
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private TencentCos tencentCos;

    @Resource
    private TencentCosConfig tencentCosConfig;


    private final String bucketName = "bookshop-1311571198";

    @RequestMapping(value = "/uploadFileTencentCos", method = RequestMethod.POST)
    public Result getUploadFileTencentCosUrl(@RequestParam("multipartFile") MultipartFile multipartFile) throws Exception {
//        System.out.println("multipartFile------------->" + multipartFile.toString());
        //判断文件不为空
        if (ObjectUtils.isEmpty(multipartFile) || multipartFile.getSize() <= 0) {
            throw new Exception("未指定文件!");
        }
        File localFile = null;
        String originalFilename = null;
        String[] filename = null;
        try {
            originalFilename = multipartFile.getOriginalFilename();
            filename = originalFilename.split("\\.");
            localFile = File.createTempFile(filename[0], filename[1]);
            //将localFile这个文件所指向的文件  上传到对应的目录
            multipartFile.transferTo(localFile);
            localFile.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
            //文件上传失败就返回错误响应
            throw new Exception("上传失败!");
        }

        if (localFile == null) {
            throw new Exception("临时文件为空！");
        }
        //2.【将文件上传到腾讯云】
        // PutObjectRequest(参数1,参数2,参数3)参数1:存储桶,参数2:指定腾讯云的上传文件路径,参数3:要上传的文件
        String key = TencentCosConfig.COS_HEAD_PORTRAIT + "/" + new Date().getTime() + "." + filename[1];
        //String key = baseUrl + "/" + originalFilename;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        //设置存储类型 默认标准型
        putObjectRequest.setStorageClass(StorageClass.Standard);
        //获得到客户端
        COSClient cosClient = tencentCosConfig.getCoSClient();
        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //putObjectResult 会返回etag
            String eTag = putObjectResult.getETag();

        } catch (CosServiceException e) {

            throw new CosServiceException(e.getMessage());
        } catch (CosClientException e) {
            throw new CosClientException(e.getMessage());
        }
        cosClient.shutdown();
        //上传路径:
        String url = tencentCos.getBaseUrl() + "/" + key;
        HashMap<String, Object> map = new HashMap<>();
        map.put("originFileName", originalFilename);
        String[] newFileName = key.split("/");
        map.put("newFileName", newFileName[1]);
        map.put("filePath", url);
        return Result.success(200, map, "success");
    }

}
